package com.example.aihub.controller;

import com.example.aihub.entity.User;
import com.example.aihub.entity.Post;
import com.example.aihub.entity.PostCategory;
import com.example.aihub.dto.UserDTO;
import com.example.aihub.service.UserService;
import com.example.aihub.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class HomeController {

    private final UserService userService;
    private final PostService postService;

    @Autowired
    public HomeController(UserService userService, PostService postService) {
        this.userService = userService;
        this.postService = postService;
    }

    @GetMapping("/")
    public String home(Model model, Authentication authentication) {
        // 获取点赞数最多的热门帖子
        List<Post> hotPosts = postService.getHotPosts(5);
        model.addAttribute("hotPosts", hotPosts);
        
        // 检查用户是否登录
        boolean isAuthenticated = authentication != null && authentication.isAuthenticated() && 
                                !(authentication.getPrincipal() instanceof String);
        model.addAttribute("isAuthenticated", isAuthenticated);
        
        // 如果用户已登录，添加用户名到模型
        if (isAuthenticated) {
            String username = authentication.getName();
            model.addAttribute("username", username);
        }
        
        // 添加热门分类到模型，用于在首页显示分类导航
        List<CategoryItem> popularCategories = getPopularCategories();
        model.addAttribute("popularCategories", popularCategories);
        
        return "index";
    }

    // 处理登录页面请求
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    // 处理注册页面请求
    @GetMapping("/register")
    public String register() {
        return "register";
    }

    // 处理帖子页面请求
    @GetMapping("/posts")
    public String posts(Model model) {
        List<Post> posts = postService.getAllPosts(0, 20); // 获取前20条帖子
        model.addAttribute("posts", posts);
        return "posts";
    }

    // 处理用户页面请求
    @GetMapping("/users")
    public String users(Model model) {
        List<User> users = userService.getAllUsers();
        
        // 将User实体转换为UserDTO，并设置统计信息
        List<UserDTO> userDTOs = users.stream().map(user -> {
            UserDTO dto = new UserDTO();
            dto.setId(user.getId());
            dto.setUsername(user.getUsername());
            dto.setEmail(user.getEmail());
            dto.setBio(user.getBio());
            dto.setAvatar(user.getAvatar());
            dto.setCreatedAt(user.getCreatedAt());
            
            // 设置统计信息
            dto.setPostCount(userService.getPostCountByUser(user));
            dto.setFollowerCount(userService.getFollowerCountByUser(user));
            dto.setFollowingCount(userService.getFollowingCountByUser(user));
            
            return dto;
        }).collect(Collectors.toList());
        
        model.addAttribute("users", userDTOs);
        return "users";
    }

    // 处理个人资料页面请求
    @GetMapping("/profile")
    public String profile(Model model) {
        // 添加登录状态检查
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || auth.getPrincipal() instanceof String) {
            // 用户未登录，重定向到登录页面
            return "redirect:/login";
        }
        
        // 获取当前登录用户
        String username = ((UserDetails) auth.getPrincipal()).getUsername();
        User user = userService.findByUsername(username).orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 获取用户的帖子
        List<Post> userPosts = postService.getPostsByUser(user);
        
        model.addAttribute("user", user);
        model.addAttribute("userPosts", userPosts);
        model.addAttribute("postCount", userPosts.size());
        model.addAttribute("followerCount", userService.getFollowerCountByUser(user)); // 使用服务获取粉丝数
        model.addAttribute("followingCount", userService.getFollowingCountByUser(user)); // 使用服务获取关注数
        
        return "profile";
    }

    // 处理帖子发布页面请求
    @GetMapping("/create-post")
    public String createPost() {
        return "create-post";
    }

    // 处理单个帖子详情页面请求
    @GetMapping("/posts/{id}")
    public String postDetail(@PathVariable Long id, Model model) {
        Post post = postService.getPostById(id)
                .orElseThrow(() -> new RuntimeException("帖子不存在"));
        model.addAttribute("post", post);
        
        // 修复currentUser问题 - 检查用户是否登录并设置合适的值
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !(auth.getPrincipal() instanceof String)) {
            UserDetails userDetails = (UserDetails) auth.getPrincipal();
            User currentUser = userService.findByUsername(userDetails.getUsername()).orElse(null);
            model.addAttribute("currentUser", currentUser);
        } else {
            // 用户未登录时，设置currentUser为null
            model.addAttribute("currentUser", null);
        }
        
        // 添加空的相关帖子列表
        model.addAttribute("relatedPosts", Collections.emptyList());
        
        return "post-detail";
    }

    // 处理分类帖子页面请求
    @GetMapping("/posts/category/{category}")
    public String getPostsByCategoryPage(
            @PathVariable String category,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model,
            Authentication authentication) {
        try {
            // 将字符串转换为PostCategory枚举
            PostCategory postCategory = PostCategory.valueOf(category.toUpperCase());
            
            // 添加分类信息到模型
            model.addAttribute("currentCategory", postCategory);
            model.addAttribute("categoryName", category);
            model.addAttribute("categoryDisplayName", postCategory.getDisplayName());
            
            // 设置分页参数
            model.addAttribute("page", page);
            model.addAttribute("size", size);
            
            // 添加热门分类到模型，用于在页面显示分类导航
            List<CategoryItem> popularCategories = getPopularCategories();
            model.addAttribute("popularCategories", popularCategories);
            
            // 检查用户是否登录
            boolean isAuthenticated = authentication != null && authentication.isAuthenticated() && 
                                    !(authentication.getPrincipal() instanceof String);
            model.addAttribute("isAuthenticated", isAuthenticated);
            
            // 如果用户已登录，添加用户名到模型
            if (isAuthenticated) {
                String username = authentication.getName();
                model.addAttribute("username", username);
            }
            
            // 返回帖子列表视图，重用现有的index视图
            return "index";
        } catch (IllegalArgumentException e) {
            // 如果分类不存在，重定向到首页
            return "redirect:/";
        }
    }

    /**
     * 获取热门分类列表
     * @return 热门分类列表
     */
    private List<CategoryItem> getPopularCategories() {
        // 选择一些热门分类显示在导航栏
        // 这里简单返回所有分类，实际应用中可以根据帖子数量或点击量来确定热门分类
        return Arrays.stream(PostCategory.values())
                .map(category -> new CategoryItem(category.name(), category.getDisplayName()))
                .collect(Collectors.toList());
    }
    
    /**
     * 内部类，用于封装分类信息传递到视图
     */
    public static class CategoryItem {
        private String name; // 分类枚举名称
        private String displayName; // 分类显示名称
        
        public CategoryItem(String name, String displayName) {
            this.name = name;
            this.displayName = displayName;
        }
        
        // Getters
        public String getName() {
            return name;
        }
        
        public String getDisplayName() {
            return displayName;
        }
    }
    
    // 处理AI工具整合页面请求
    @GetMapping("/ai-tools")
    public String aiTools(Model model, Authentication authentication) {
        // 检查用户是否登录
        boolean isAuthenticated = authentication != null && authentication.isAuthenticated() && 
                                !(authentication.getPrincipal() instanceof String);
        model.addAttribute("isAuthenticated", isAuthenticated);
        
        // 如果用户已登录，添加用户名到模型
        if (isAuthenticated) {
            String username = authentication.getName();
            model.addAttribute("username", username);
        }
        
        return "ai-tools";
    }
}